package com.ty.zls.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.qmuiteam.qmui.util.QMUIColorHelper;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.ty.zls.MainActivity;
import com.ty.zls.R;
import com.ty.zls.bean.Constants;
import com.ty.zls.util.CommonUtil;
import com.ty.zls.util.HttpUtil;
import com.ty.zls.util.StringUtils;
import com.ty.zls.util.StrogeUtil;
import com.xuexiang.xupdate.XUpdate;

import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class LoginActivity extends BaseActivity implements View.OnClickListener {


    @ViewInject(R.id.et_login_username)
    private EditText et_login_username;
    @ViewInject(R.id.et_login_pwd)
    private EditText et_login_pwd;
    @ViewInject(R.id.bt_login_submit)
    private Button bt_login_submit;
    @ViewInject(R.id.iv_login_username_del)
    private ImageView iv_login_username_del;
    @ViewInject(R.id.iv_login_pwd_del)
    private ImageView iv_login_pwd_del;
    //数据
    Map<String, String> map = new HashMap<>();
    // popup
    private QMUIPopup namepopUp;
    private QMUIPopup pwdPopUp;
    //提示
    private QMUITipDialog tipDialog;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        QMUIStatusBarHelper.translucent(this, QMUIColorHelper.setColorAlpha(0x000000, 0));
        init();
    }

    /**
     * 组件初始化
     */
    private void init() {
        x.view().inject(this);
        bt_login_submit.setOnClickListener(this);
        iv_login_username_del.setOnClickListener(this);
        iv_login_pwd_del.setOnClickListener(this);

        //清除图标显示
        et_login_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtils.isNotEmpty(s.toString())) {
                    if (iv_login_username_del.getVisibility() != View.VISIBLE) {
                        iv_login_username_del.setVisibility(View.VISIBLE);
                    }
                } else if (iv_login_username_del.getVisibility() != View.GONE) {
                    iv_login_username_del.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        et_login_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtils.isNotEmpty(s.toString())) {
                    if (iv_login_pwd_del.getVisibility() != View.VISIBLE) {
                        iv_login_pwd_del.setVisibility(View.VISIBLE);
                    }
                } else if (iv_login_pwd_del.getVisibility() != View.GONE) {
                    iv_login_pwd_del.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login_submit:
                StrogeUtil.rmToken(this);
                dosubmit();
                break;
            case R.id.iv_login_username_del:
                et_login_username.setText("");
                break;
            case R.id.iv_login_pwd_del:
                et_login_pwd.setText("");
                break;
        }

    }

    private void initUsernamePopup() {
        if (this.namepopUp == null) {
            namepopUp = new QMUIPopup(this, QMUIPopup.DIRECTION_NONE);
            TextView textView = new TextView(this);
            textView.setLayoutParams(namepopUp.generateLayoutParam(
                    QMUIDisplayHelper.dp2px(this, 250),
                    WRAP_CONTENT
            ));
            textView.setLineSpacing(QMUIDisplayHelper.dp2px(this, 4), 1.0f);
            int padding = QMUIDisplayHelper.dp2px(this, 20);
            textView.setPadding(padding, padding, padding, padding);
            textView.setText("请填写用户名");
            textView.setTextColor(ContextCompat.getColor(this, R.color.qmui_config_color_gray_5));
            namepopUp.setContentView(textView);
        }
    }

    private void initPwdPopup() {
        if (this.pwdPopUp == null) {
            pwdPopUp = new QMUIPopup(this, QMUIPopup.DIRECTION_NONE);
            TextView textView = new TextView(this);
            textView.setLayoutParams(pwdPopUp.generateLayoutParam(
                    QMUIDisplayHelper.dp2px(this, 250),
                    WRAP_CONTENT
            ));
            textView.setLineSpacing(QMUIDisplayHelper.dp2px(this, 4), 1.0f);
            int padding = QMUIDisplayHelper.dp2px(this, 20);
            textView.setPadding(padding, padding, padding, padding);
            textView.setText("请填写密码");
            textView.setTextColor(ContextCompat.getColor(this, R.color.qmui_config_color_gray_5));
            pwdPopUp.setContentView(textView);
        }
    }

    /**
     * 登陆尝试
     */
    private void dosubmit() {
        String userName = et_login_username.getText().toString();
        if (StringUtils.isEmpty(userName)) {
            initUsernamePopup();
            namepopUp.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
            namepopUp.setPreferredDirection(QMUIPopup.DIRECTION_TOP);
            namepopUp.show(et_login_username);
            return;
        }
        String password = et_login_pwd.getText().toString();
        if (StringUtils.isEmpty(password)) {
            initPwdPopup();
            namepopUp.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
            namepopUp.setPreferredDirection(QMUIPopup.DIRECTION_TOP);
            namepopUp.show(et_login_pwd);
            return;
        }
        map.put("loginName", userName);
        map.put("password", password);
        new MyTask().execute(map);
    }


    /**
     * 任务
     */
    class MyTask extends AsyncTask<Map<String, String>, Void, Map<String, Object>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tipDialog = new QMUITipDialog.Builder(LoginActivity.this)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord("登录中")
                    .create();
            tipDialog.show();
        }

        @Override
        protected Map<String, Object> doInBackground(Map<String, String>... maps) {
            Map<String, Object> data = new HashMap<>();
            try {
                JSONObject result = HttpUtil.post(maps[0], HttpUtil.LOGIN);
                int code = result.optInt("code");
                data.put("code", code);
                data.put("msg", result.optString("msg"));
                data.put("name", result.optString("name"));
                data.put("token", result.optString("token"));
            } catch (Exception e) {
                data.put("code", Constants.ERROR_CODE);
            }
            return data;
        }

        @Override
        protected void onPostExecute(Map<String, Object> map) {
            super.onPostExecute(map);
            tipDialog.dismiss();
            String title = "";
            final Integer code = (Integer) map.get("code");
            if(Constants.ERROR_CODE.equals(code)){
                if(!CommonUtil.isNetworkAvailable(LoginActivity.this)){
                    title = "发送失败,请检查网络是否连接";
                }else{
                    title = "发送失败,请稍后重试";
                }
                tipDialog = new QMUITipDialog.Builder(LoginActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord(title)
                        .create();
            }else if(Constants.FAIL_CODE.equals(code)){
                tipDialog = new QMUITipDialog.Builder(LoginActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord((String)map.get("msg"))
                        .create();
            }else if(Constants.SUCCESS_CODE.equals(code)){
                tipDialog = new QMUITipDialog.Builder(LoginActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                        .setTipWord("登录成功")
                        .create();
                //存储用户名 token
                StrogeUtil.setStringPs(LoginActivity.this,StrogeUtil.user,StrogeUtil.token,(String)map.get("token"));
                StrogeUtil.setStringPs(LoginActivity.this,StrogeUtil.user,"loginName",(String)map.get("name"));
            }
            tipDialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tipDialog.dismiss();
                    if(Constants.SUCCESS_CODE.equals(code)){
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        LoginActivity.this.finish();
                    }
                }
            },1500);
        }
    }
}
